package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.ColumnSortPojo;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.InstockProductEntity;
import com.xbongbong.saas.domain.entity.OutstockProductEntity;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.competitor.CompetitorEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.ContractProductTypeEnum;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.ListOptionEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.model.CompetitorModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.InstockProductModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.service.toolbox.help.FundSetHelp;
import com.xbongbong.sys.domain.entity.UserConfigEntity;
import com.xbongbong.sys.enums.UserConfigEnum;
import com.xbongbong.sys.model.UserConfigModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/2/28 17:18
 * @since v1.0
 */
@Component
public class SaasHelp {
    @Resource
    private EsHelper esHelper;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private InstockProductModel instockProductModel;
    @Resource
    private UserConfigModel userConfigModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private FundSetHelp fundSetHelp;
    @Resource
    private CompetitorModel competitorModel;

    /**
     * 获取合同剩余未出库产品信息及数量
     * @param corpid 公司id
     * @param contractIdIn 合同id
     */
    public List<ContractProductEntity> getContractProductWaitOutStock(String corpid, List<Long> contractIdIn) throws XbbException{
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("contractIdIn", contractIdIn);
        param.put("type",ContractProductTypeEnum.CONTNRACT.getCode());
        param.put("del", 0);
        param.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
        List<ContractProductEntity> contractProductEntityList = contractProductModel.findEntitys(param);
//        List<Long> outStockIdList = new ArrayList<>();
//        BoolQueryBuilder boolQueryBuilder = boolQuery();
//        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
//        boolQueryBuilder.filter(termsQuery("data." + OutstockEnum.REF_ID.getAttr(),contractIdIn));
//        boolQueryBuilder.filter(termQuery("data." + OutstockEnum.TYPE.getAttr(),OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode()));
//        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
//        List<OutstockEntityExt> outstockEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OUTSTOCK,boolQueryBuilder,OutstockEntityExt.class,Arrays.asList(FieldTypeEnum.DATAID.getAlias(),OutstockEnum.getAttrConnectData(OutstockEnum.REF_ID)));
//        Map<Long,Long> contractIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//        for (OutstockEntityExt outstockEntityExt : outstockEntityExtList){
//            outStockIdList.add(outstockEntityExt.getDataId());
//            Long contractId = outstockEntityExt.getData().getLong(OutstockEnum.REF_ID.getAttr());
//            contractIdMap.put(outstockEntityExt.getDataId(),contractId);
//        }
        Map<String, Double> productEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//        if (!outStockIdList.isEmpty()){
//            param.clear();
//            param.put("corpid", corpid);
//            param.put("outstockIdIn", outStockIdList);
//            param.put("del", 0);
//            List<OutstockProductEntity> outstockProductEntityList = outstockProductModel.findEntitys(param);
//            for (OutstockProductEntity entity : outstockProductEntityList){
//                String key;
//                if (Objects.isNull(entity.getRefProductId())){
//                    key = contractIdMap.get(entity.getOutWarehouseId()) + "_" + entity.getProductId();
//                }else {
//                    key = contractIdMap.get(entity.getOutWarehouseId()) + "_" + entity.getProductId() + "_" + entity.getRefProductId();
//                }
//                Double num = productEntityMap.getOrDefault(key,0D);
//                num += entity.getProductNum();
//                productEntityMap.put(key,num);
//            }
//        }
        param.clear();
        param.put("corpid", corpid);
        param.put("refIdIn", contractIdIn);
        param.put("type", OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode());
        param.put("del", 0);
        param.put("columns","ref_id,product_id,ref_product_id,product_num");
        param.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
        List<OutstockProductEntity> outstockProductEntityList = outstockProductModel.findEntitys(param);
        for (OutstockProductEntity entity : outstockProductEntityList){
            String key;
            if (Objects.isNull(entity.getRefProductId())){
                key = entity.getRefId() + "_" + entity.getProductId();
            }else {
                key = entity.getRefId() + "_" + entity.getProductId() + "_" + entity.getRefProductId();
            }
            Double num = productEntityMap.getOrDefault(key,0D);
            num += entity.getProductNum();
            productEntityMap.put(key,num);
        }

        Iterator<ContractProductEntity> iterator = contractProductEntityList.iterator();
        while (iterator.hasNext()) {
            ContractProductEntity entity = iterator.next();
            String key = entity.getContractId() + "_" + entity.getProductId() + "_" + entity.getId();
            //先匹配新数据
            if (!productEntityMap.containsKey(key)) {
                //在匹配老数据
                key = entity.getContractId() + "_" + entity.getProductId();
                if (!productEntityMap.containsKey(key)) {
                    entity.setWaitOutStockNum(entity.getProductNum());
                    continue;
                }
            }
            Double outstockNum = productEntityMap.get(key);
            double productNum = entity.getProductNum() == null ? 0D : entity.getProductNum();
            double leftProductNum = Arith.sub(productNum, outstockNum);
            if (leftProductNum < 0.00000001) {
                iterator.remove();
                productEntityMap.put(key,Arith.sub(outstockNum,productNum));
            } else {
                entity.setProductNum(leftProductNum);
                productEntityMap.put(key,0D);
            }
            entity.setWaitOutStockNum(productEntityMap.getOrDefault(key,0D));
        }
        return contractProductEntityList;
    }

    /**
     * 获取采购合同剩余未入库产品信息及数量
     * @param corpid 公司id
     * @param purchaseIdIn 合同id
     */
    public List<PurchaseProductEntity> getPurchasetProductWaitInStock(String corpid, List<Long> purchaseIdIn) throws XbbException{
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("purchaseIdIn", purchaseIdIn);
        param.put("del", 0);
        param.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
        List<PurchaseProductEntity> purchaseProductEntityList = purchaseProductModel.findEntitys(param);
        Map<String, Double> productEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.clear();
        param.put("corpid", corpid);
        param.put("type",InstockTypeEnum.PURCHASE_INSTOCK.getCode());
        param.put("refIdIn", purchaseIdIn);
        param.put("del", 0);
        param.put("columns","ref_id,product_id,ref_product_id,product_num");
        param.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);
        List<InstockProductEntity> instockProductEntityList = instockProductModel.findEntitys(param);
        for (InstockProductEntity entity : instockProductEntityList){
            String key;
            if (Objects.isNull(entity.getRefProductId())){
                key = entity.getRefId() + "_" + entity.getProductId();
            }else {
                key = entity.getRefId() + "_" + entity.getProductId() + "_" + entity.getRefProductId();
            }
            Double num = productEntityMap.getOrDefault(key,0D);
            num += entity.getProductNum();
            productEntityMap.put(key,num);
        }

        Iterator<PurchaseProductEntity> iterator = purchaseProductEntityList.iterator();
        while (iterator.hasNext()) {
            PurchaseProductEntity entity = iterator.next();
            String key = entity.getPurchaseSheetId() + "_" + entity.getProductId() + "_" + entity.getId();
            //先匹配新数据
            if (!productEntityMap.containsKey(key)) {
                //在匹配老数据
                key = entity.getPurchaseSheetId() + "_" + entity.getProductId();
                if (!productEntityMap.containsKey(key)) {
                    entity.setWaitInstockNum(entity.getProductNum());
                    continue;
                }
            }
            Double instockNum = productEntityMap.get(key);
            Double productNum = entity.getProductNum();
            double leftProductNum = Arith.sub(productNum, instockNum);
            if (leftProductNum < 0.00000001) {
                iterator.remove();
                productEntityMap.put(key,Arith.sub(instockNum,productNum));
            } else {
                entity.setProductNum(leftProductNum);
                productEntityMap.put(key,0D);
            }
            entity.setWaitInstockNum(productEntityMap.getOrDefault(key,0D));
        }
        return purchaseProductEntityList;
    }

    /**
     * 获取待入库产品维度数量信息
     */
    public List<PurchaseProductEntity> getWaitInStockProduct(String corpid, List<PurchaseProductEntity> purchaseProductEntityList) throws XbbException{
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> purchaseIdIn = new ArrayList<>();
        purchaseProductEntityList.forEach(purchaseProductEntity -> {
            purchaseIdIn.add(purchaseProductEntity.getId());
        });
        param.clear();
        param.put("corpid", corpid);
        param.put("type",InstockTypeEnum.PURCHASE_INSTOCK.getCode());
        param.put("refProductIdIn", purchaseIdIn);
        param.put("del", 0);
        param.put("columns","ref_id,product_id,ref_product_id,product_num");
        List<InstockProductEntity> instockProductEntityList = instockProductModel.findEntitys(param);
        Map<String, Double> productEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (InstockProductEntity entity : instockProductEntityList){
            String key;
            if (Objects.isNull(entity.getRefProductId())){
                key = entity.getRefId() + "_" + entity.getProductId();
            }else {
                key = entity.getRefId() + "_" + entity.getProductId() + "_" + entity.getRefProductId();
            }
            Double num = productEntityMap.getOrDefault(key,0D);
            num += entity.getProductNum();
            productEntityMap.put(key,num);
        }
        Iterator<PurchaseProductEntity> iterator = purchaseProductEntityList.iterator();
        while (iterator.hasNext()) {
            PurchaseProductEntity entity = iterator.next();
            String key = entity.getPurchaseSheetId() + "_" + entity.getProductId() + "_" + entity.getId();
            //先匹配新数据
            if (!productEntityMap.containsKey(key)) {
                //在匹配老数据
                key = entity.getPurchaseSheetId() + "_" + entity.getProductId();
                if (!productEntityMap.containsKey(key)) {
                    entity.setWaitInstockNum(entity.getProductNum());
                    continue;
                }
            }
            Double instockNum = productEntityMap.get(key);
            Double productNum = entity.getProductNum();
            double leftProductNum = Arith.sub(productNum, instockNum);
            if (leftProductNum < 0.00000001 && leftProductNum != 0.00) {
                iterator.remove();
                productEntityMap.put(key,Arith.sub(instockNum,productNum));
            } else {
                entity.setProductNum(leftProductNum);
                productEntityMap.put(key,0D);
            }
            entity.setWaitInstockNum(productEntityMap.getOrDefault(key,0D));
        }
        return purchaseProductEntityList;
    }

    /**
     * 获取合同缺货信息
     * @param corpid 公司id
     * @param contractProductEntityList 合同产品
     */
    public JSONArray getWaitPurchaseInfo(String corpid, List<ContractProductEntity> contractProductEntityList) throws XbbException{
        List<Long> productIdIn = new ArrayList<>();
        for (ContractProductEntity entity : contractProductEntityList){
            productIdIn.add(entity.getProductId());
        }
        if (productIdIn.isEmpty()) {
            return new JSONArray();
        }
        Map<Long,Double> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(), productIdIn));
        boolQueryBuilder.mustNot(termQuery("data." + ProductEnum.PARENT_ID.getAttr(), 0));
        // 限制返回值
        List<String> fieldList = Arrays.asList(StringConstant.SAAS_LINK_BUSINESS_ID, ProductEnum.STOCK.getAttr());
//        List<ProductEntityExt> productEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, ProductEntityExt.class, fieldList);
        SearchRequest searchRequest = EsUtil.simplePackageForQueryForPage(IndexTypeEnum.IDX_SAAS_PRODUCT,boolQueryBuilder,fieldList, 0, productIdIn.size());
        XbbAggregatedPage<ProductEntityExt> result = xbbElasticsearchRestTemplate.queryForPages(searchRequest,ProductEntityExt.class);
        List<ProductEntityExt> productEntityExtList = result.getContent();
        for (ProductEntityExt entity : productEntityExtList){
            productMap.put(entity.getId(),entity.getData().getDouble(ProductEnum.STOCK.getAttr()));
        }
        JSONArray productArray = new JSONArray();
        for (ContractProductEntity entity : contractProductEntityList){
            Long productId = entity.getProductId();
            Double num = entity.getProductNum();
            Double stock = productMap.get(productId);
            if (Objects.equals(stock, null)) {
                continue;
            }
            double needPurchaseNum = Arith.sub(num, stock);
            if (Double.compare(needPurchaseNum, 0D) > 0) {
                JSONObject item = new JSONObject();
                item.put("productId", productId);
                item.put("num", needPurchaseNum);
                productArray.add(item);
            }
        }
        return productArray;
    }

    /**
     * 处理返回的应收账期特殊字段(客户、应收款)
     *
     * @param paasFormDataEsListVO
     */
    public void handleListSpecialField(PaasFormDataEsListVO paasFormDataEsListVO, int businessType) {
        String attr = "";
        if ((XbbRefTypeEnum.PAYMENT.getCode()) == (businessType)) {
            attr = PaymentEnum.RECEIVABLE_PERIOD.getAttr();
        }else if ((XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) == (businessType)) {
            attr = CustomerManagementEnum.RECEIVABLE_PERIOD.getAttr();
        }else if ((XbbRefTypeEnum.CONTRACT.getCode()) == (businessType)) {
            attr = ContractEnum.RECEIVABLE_PERIOD.getAttr();
        }
        if (!Objects.isNull(paasFormDataEsListVO)) {
            List<PaasFormDataEntityExt> paasFormDataESList = paasFormDataEsListVO.getPaasFormDataESList();
            if (CollectionsUtil.isNotEmpty(paasFormDataESList)) {
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                    //sourceData里面的账期 处理成对象格式
                    JSONObject jsonObjectSen = paasFormDataEntityExt.getSourceData();
                    if (!Objects.isNull(jsonObjectSen)) {
                        Object objSen = jsonObjectSen.get(attr);
                        if (!Objects.isNull(objSen)) {
                            jsonObjectSen.put(attr ,objSen);
                        }
                    }
                    paasFormDataEntityExt.setSourceData(jsonObjectSen);
                }
            }
        }

    }

    /**
     * @Author mingliang
     * @Description 获得显示的列表与操作列表
     * @param formDataListDTO
     * @param explainList
     * @param summary
     **/
    public JSONObject getShowFieldAttrList(FormDataListDTO formDataListDTO, List<FieldAttrEntity> explainList, JSONArray summary) throws XbbException {
        JSONObject result = new JSONObject();
        Integer saasMark = formDataListDTO.getSaasMark();
        String laneListShowFieldConfigAlias = UserConfigEnum.LANE_LIST_SHOW_FIELD.getAlias()+"_" + formDataListDTO.getAppId() + "_" + formDataListDTO.getFormId();
        Map<String, Object> params = new HashMap<>();
        params.put("configAlias", laneListShowFieldConfigAlias);
        params.put("userId", formDataListDTO.getUserId());
        params.put("corpid", formDataListDTO.getCorpid());
        params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        List<UserConfigEntity> userConfigList = userConfigModel.list(params);
        List<FieldAttrEntity> showList = new ArrayList<>();
        List<FieldAttrEntity> showOperationList = new ArrayList<>();
        if (CollectionsUtil.isEmpty(userConfigList)) {
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
                for (int i = 0; i < explainList.size(); i++) {
                    FieldAttrEntity fieldAttrEntity = explainList.get(i);
                    String attr = fieldAttrEntity.getAttr();
                    //筛选出操作按钮，操作按钮跟进记录不需要
                    if (attr.contains("option") && !Objects.equals(attr, ListOptionEnum.FLOW.getAttr())) {
                        showOperationList.add(fieldAttrEntity);
                        continue;
                    }
                    if (Objects.equals(FieldTypeEnum.LOCATION.getType(),fieldAttrEntity.getFieldType())){
                        continue;
                    }
                    //摘要
                    for (int j = 0; j < summary.size(); j++) {
                        JSONObject temp = summary.getJSONObject(j);
                        if (Objects.equals(attr, temp.getString("attr"))) {
                            showList.add(fieldAttrEntity);
                            break;
                        }
                    }
                }
                if (CollectionsUtil.isEmpty(showList)) {
                    removeExplainByBusinessType(formDataListDTO.getBusinessType(),explainList);
                    int count = 0;
                    for (int i = 0; i < explainList.size(); i++) {
                        FieldAttrEntity fieldAttrEntity = explainList.get(i);
                        String attr = fieldAttrEntity.getAttr();
                        if (count == 5) {
                            break;
                        }
                        if (Objects.equals(FieldTypeEnum.SEPARATOR.getType(), fieldAttrEntity.getFieldType())
                                || Objects.equals(FieldTypeEnum.LOCATION.getType(), fieldAttrEntity.getFieldType())
                                || Objects.equals(FieldTypeEnum.SUB_FORM.getType(), fieldAttrEntity.getFieldType())
                                || Objects.equals(FieldTypeEnum.IMAGE.getType(), fieldAttrEntity.getFieldType())
                                || Objects.equals(FieldTypeEnum.UPLOAD.getType(), fieldAttrEntity.getFieldType())) {
                            continue;
                        }

                        //筛选出操作按钮
                        if (!attr.contains("option")) {
                            showList.add(fieldAttrEntity);
                            count++;
                        }
                    }
                }
            } else if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
                int count = 0;
                for (int i = 0; i < explainList.size(); i++) {
                    FieldAttrEntity fieldAttrEntity = explainList.get(i);
                    String attr = fieldAttrEntity.getAttr();
                    if (count == 5) {
                        break;
                    }
                    if (Objects.equals(FieldTypeEnum.SEPARATOR.getType(), fieldAttrEntity.getFieldType())
                            || Objects.equals(FieldTypeEnum.LOCATION.getType(), fieldAttrEntity.getFieldType())
                            || Objects.equals(FieldTypeEnum.SUB_FORM.getType(), fieldAttrEntity.getFieldType())
                            || Objects.equals(FieldTypeEnum.IMAGE.getType(), fieldAttrEntity.getFieldType())
                            || Objects.equals(FieldTypeEnum.UPLOAD.getType(), fieldAttrEntity.getFieldType())) {
                        continue;
                    }

                    //筛选出操作按钮
                    if (attr.contains("option")) {
                        showOperationList.add(fieldAttrEntity);
                    }else {
                        showList.add(fieldAttrEntity);
                        count++;
                    }
                }
            }

            result.put("showList", showList);

        } else {
            UserConfigEntity userConfigEntity = userConfigList.get(0);
            List<String> stringList = JSONArray.parseArray(userConfigEntity.getConfigValue(), String.class);
            for (String temp : stringList) {
                for (FieldAttrEntity fieldAttrEntity : explainList) {
                    if (Objects.equals(temp, fieldAttrEntity.getAttr())) {
                        if (!Objects.equals(fieldAttrEntity.getAttr(), ListOptionEnum.FLOW.getAttr())){
                            if (fieldAttrEntity.getAttr().contains("option")) {
                                showOperationList.add(fieldAttrEntity);
                            } else {
                                showList.add(fieldAttrEntity);
                            }
                        }
                    }
                }
            }
            //数据当中有数据需要对showList排序
            String laneListSortFieldConfigAlias = UserConfigEnum.LANE_LIST_SORT_FIELD.getAlias()+"_" + formDataListDTO.getAppId() + "_" + formDataListDTO.getFormId();
            Map<String, Object> map = new HashMap<>();
            map.put("configAlias", laneListSortFieldConfigAlias);
            map.put("userId", formDataListDTO.getUserId());
            map.put("corpid", formDataListDTO.getCorpid());
            map.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<UserConfigEntity> sortAttrList = userConfigModel.list(map);
            List<FieldAttrEntity> sortShowList = new ArrayList<>();
            if (CollectionsUtil.isNotEmpty(sortAttrList)) {
                UserConfigEntity temp = sortAttrList.get(0);
                List<ColumnSortPojo> columnSortPojoList = JSONArray.parseArray(temp.getConfigValue(), ColumnSortPojo.class);
                for (ColumnSortPojo pojo : columnSortPojoList) {
                    for (FieldAttrEntity fieldAttrEntity : showList) {
                        if (Objects.equals(pojo.getAttr(), fieldAttrEntity.getAttr())) {
                            sortShowList.add(fieldAttrEntity);
                            break;
                        }
                    }
                }
            }
            //判断排序后的数据中有没有标签,含有标签将标签移动到第二个
            int index = 1;
            for (int i = 0; i < sortShowList.size(); i++) {
                FieldAttrEntity fieldAttrEntity = sortShowList.get(i);
                if (Objects.equals(FieldTypeEnum.LABEL.getType(), fieldAttrEntity.getFieldType())) {
                    index = i;
                }
            }
            if (index != 1) {
                FieldAttrEntity labelEntity = sortShowList.get(index);
                sortShowList.remove(index);
                sortShowList.add(1, labelEntity);
            }
            result.put("showList", sortShowList);
        }
        result.put("showOperationList", showOperationList);
        //查询统计列
        String laneCountFieldConfigAlias = UserConfigEnum.LANE_COUNT_FIELD.getAlias()+"_" + formDataListDTO.getAppId() + "_" + formDataListDTO.getFormId();
        params.clear();
        params.put("configAlias", laneCountFieldConfigAlias);
        params.put("userId", formDataListDTO.getUserId());
        params.put("corpid", formDataListDTO.getCorpid());
        params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        List<UserConfigEntity> countFieldEntity = userConfigModel.list(params);
        String countField = null;
        if (CollectionsUtil.isNotEmpty(countFieldEntity)) {
            countField = countFieldEntity.get(0).getConfigValue();
        }
        result.put("countField", countField);
        return result;
    }

    /**
     * @Author mingliang
     * @Description 获得统计的中文名
     * @param explainList
     * @param formDataListDTO
     **/
    public String getCountTitleNameByAttr(List<FieldAttrEntity> explainList, FormDataListDTO formDataListDTO) {
        String countTitle = "";
        String laneCountFieldConfigAlias = UserConfigEnum.LANE_COUNT_FIELD.getAlias()+"_" + formDataListDTO.getAppId() + "_" + formDataListDTO.getFormId();
        Map<String, Object> params = new HashMap<>();
        params.put("configAlias", laneCountFieldConfigAlias);
        params.put("userId", formDataListDTO.getUserId());
        params.put("corpid", formDataListDTO.getCorpid());
        params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        List<UserConfigEntity> countConfig = userConfigModel.list(params);
        if (CollectionsUtil.isNotEmpty(countConfig)){
            String configValue = countConfig.get(0).getConfigValue();
            if (StringUtil.isNotEmpty(configValue)) {
                for (FieldAttrEntity temp : explainList) {
                    if (Objects.equals(temp.getAttr(),configValue)){
                        countTitle = temp.getAttrName();
                        break;
                    }
                }
            }
        }
        return countTitle;
    }

    /**
     * 过滤掉不在泳道视图显示的复杂的系统字段和自定义字段
     *
     * @param businessType
     * @param explainList
     * @throws XbbException
     */
    public void removeExplainByBusinessType(Integer businessType, List<FieldAttrEntity> explainList) throws XbbException {
        if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
            explainList.removeIf(e -> Objects.equals(CustomerManagementEnum.PHONE.getAttr(), e.getAttr())
                    || Objects.equals(CustomerManagementEnum.CONTACT_NAME.getAttr(), e.getAttr())
                    || Objects.equals(CustomerManagementEnum.CONTACT_PHONE.getAttr(), e.getAttr())
                    || Objects.equals(CustomerManagementEnum.SCORE.getAttr(), e.getAttr())
                    || Objects.equals(CustomerManagementEnum.FILE.getAttr(), e.getAttr())
                    || Objects.equals(FieldTypeEnum.SEPARATOR.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.CONTACT_NUMBER.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.LOCATION.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.SUB_FORM.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.IMAGE.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.UPLOAD.getType(), e.getFieldType())
                    || Objects.equals(e.getAttr(), ListOptionEnum.FLOW.getAttr())//操作按钮跟进记录不需要
            );
        } else if (Objects.equals(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), businessType)) {
            explainList.removeIf(e -> Objects.equals(SalesOpportunityEnum.PRODUCTS.getAttr(), e.getAttr())
                    || Objects.equals(FieldTypeEnum.SEPARATOR.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.CONTACT_NUMBER.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.LOCATION.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.SUB_FORM.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.IMAGE.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.UPLOAD.getType(), e.getFieldType())
                    || Objects.equals(e.getAttr(), ListOptionEnum.FLOW.getAttr())//操作按钮跟进记录不需要
            );
        } else if (Objects.equals(XbbRefTypeEnum.CLUE.getCode(), businessType)) {
            explainList.removeIf(e -> Objects.equals(ClueEnum.PHONE.getAttr(), e.getAttr())
                    || Objects.equals(FieldTypeEnum.SEPARATOR.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.CONTACT_NUMBER.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.LOCATION.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.SUB_FORM.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.IMAGE.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.UPLOAD.getType(), e.getFieldType())
                    || Objects.equals(e.getAttr(), ListOptionEnum.FLOW.getAttr())//操作按钮跟进记录不需要
            );
        } else if (Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), businessType)) {
            explainList.removeIf(e -> Objects.equals(ContractEnum.PRODUCT.getAttr(), e.getAttr())
                    || Objects.equals(ContractEnum.ADD_PAYMENT_SHEET.getAttr(), e.getAttr())
                    || Objects.equals(ContractEnum.ADD_WRITE_OFF_PREPAYMENT.getAttr(), e.getAttr())
                    || Objects.equals(ContractEnum.ADD_PAYMENT.getAttr(), e.getAttr())
                    || Objects.equals(ContractEnum.RECEIVABLE_PERIOD.getAttr(), e.getAttr())
                    || Objects.equals(FieldTypeEnum.SEPARATOR.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.CONTACT_NUMBER.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.LOCATION.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.SUB_FORM.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.IMAGE.getType(), e.getFieldType())
                    || Objects.equals(FieldTypeEnum.UPLOAD.getType(), e.getFieldType())
                    || Objects.equals(e.getAttr(), ListOptionEnum.FLOW.getAttr())//操作按钮跟进记录不需要
            );
        }
    }

    /**
     * 解析机会表单数据中的竞争对手相关字段
     * date: 2022/8/25 4:19 下午
     * @author yingjf
     * @param paasFormDataEsListVO:
     * @param businessType:
     */
    public void handleListCompetitor(PaasFormDataEsListVO paasFormDataEsListVO, int businessType){
        if(!Objects.equals(businessType,XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())){
            return;
        }
        if (Objects.nonNull(paasFormDataEsListVO)) {
            List<PaasFormDataEntityExt> paasFormDataESList = paasFormDataEsListVO.getPaasFormDataESList();
            String corpid = paasFormDataESList.get(0).getCorpid();
            Set<Long> competitorIdSet = new HashSet<>();
            if (CollectionsUtil.isNotEmpty(paasFormDataESList)) {
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                    JSONObject data = paasFormDataEntityExt.getData();
                    if(Objects.nonNull(data)){
                        Long winId = data.getLong(SalesOpportunityEnum.WIN_COMPETITOR.getAttr());
                        competitorIdSet.add(winId);
                        JSONArray jsonArray = data.getJSONArray(SalesOpportunityEnum.LINK_COMPETITOR.getAttr());
                        if(CollectionsUtil.isNotEmpty(jsonArray)){
                            for(Object item: jsonArray){
                                long id = Long.parseLong(item.toString());
                                competitorIdSet.add(id);
                            }
                        }
                    }
                }
                List<CompetitorEntity> competitorEntityList = competitorModel.getByKeys(competitorIdSet, corpid);
                Map<Long,String> nameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                competitorEntityList.forEach(item->{
                    nameMap.put(item.getId(),item.getData().getString(CompetitorEnum.NAME.getAttr()));
                });

                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                    JSONObject data = paasFormDataEntityExt.getData();
                    if(Objects.nonNull(data)){
                        Long winId = data.getLong(SalesOpportunityEnum.WIN_COMPETITOR.getAttr());
                        JSONObject winJsonObject = new JSONObject();
                        winJsonObject.put("id",winId);
                        winJsonObject.put("name",nameMap.get(winId));
                        winJsonObject.put("businessType",XbbRefTypeEnum.COMPETITOR.getCode());
                        winJsonObject.put("saasMark",SaasMarkEnum.SAAS.getCode());
                        JSONArray winJsonArray = new JSONArray();
                        winJsonArray.add(winJsonObject);
                        JSONArray jsonArray = new JSONArray();
                        JSONArray linkCompetitorJsonArray = data.getJSONArray(SalesOpportunityEnum.LINK_COMPETITOR.getAttr());
                        if(CollectionsUtil.isNotEmpty(linkCompetitorJsonArray)){
                            for(Object item: linkCompetitorJsonArray){
                                long id = Long.parseLong(item.toString());
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("id",id);
                                jsonObject.put("name",nameMap.get(id));
                                jsonObject.put("businessType",XbbRefTypeEnum.COMPETITOR.getCode());
                                jsonObject.put("saasMark",SaasMarkEnum.SAAS.getCode());
                                jsonArray.add(jsonObject);
                            }
                        }
                        data.put(SalesOpportunityEnum.WIN_COMPETITOR.getAttr(),winJsonArray);
                        data.put(SalesOpportunityEnum.LINK_COMPETITOR.getAttr(),jsonArray);
                    }
                }

            }


        }


    }
}
